import requests 
import re
import pandas

stock_list = []
stock_list_thead = ["序号","股票代码","企业名称","最新价","涨跌幅","涨跌额","成交量(手)","成交额","振幅","最高","最低","今开","昨收","量比","换手率","市盈率","市净率"]
headers = {
    "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0",
    "referer":"https://quote.eastmoney.com/center/gridlist.html",
    "cookie":"qgqp_b_id=559f798d08d6e274f75616a4ad9dd96a; websitepoptg_api_time=1747148800255; st_si=75406587337460; st_asi=delete; fullscreengg=1; fullscreengg2=1; st_pvi=30028216726328; st_sp=2025-05-13%2023%3A06%3A40; st_inirUrl=https%3A%2F%2Fcn.bing.com%2F; st_sn=8; st_psi=20250513234938993-113200301321-2917366166"
}
for page_number in range(1,287):
    url = f"https://push2.eastmoney.com/api/qt/clist/get?np=1&fltt=1&invt=2&cb=jQuery37106000471697730656_1747151378150&fs=m%3A0%2Bt%3A6%2Cm%3A0%2Bt%3A80%2Cm%3A1%2Bt%3A2%2Cm%3A1%2Bt%3A23%2Cm%3A0%2Bt%3A81%2Bs%3A2048&fields=f12%2Cf13%2Cf14%2Cf1%2Cf2%2Cf4%2Cf3%2Cf152%2Cf5%2Cf6%2Cf7%2Cf15%2Cf18%2Cf16%2Cf17%2Cf10%2Cf8%2Cf9%2Cf23&fid=f3&pn={page_number}&pz=20&po=1&dect=1&ut=fa5fd1943c7b386f172d6893dbfba10b&wbp2u=%7C0%7C0%7C0%7Cweb&_=1747151378154"
    response = requests.get(url,headers=headers)
    # print(response.status_code)

    Stock_code = re.findall('"f12":"(.*?)"',response.text) #股票代码
    Company_Name = re.findall('"f14":"(.*?)"',response.text) #企业名称
    Latest_Price = re.findall('"f2":(.*?),',response.text) #最新价
    Original_Change_Percentage = re.findall('"f3":(.*?),',response.text) #涨跌幅
    Change_Amount = re.findall('"f4":(.*?),',response.text) #涨跌额
    Original_Volume_in_lots = re.findall('"f5":(.*?),',response.text) #成交量(手)
    Original_Turnover = re.findall('"f6":(.*?),',response.text) #成交额(亿)
    Original_Price_Range = re.findall('"f7":(.*?),',response.text) #振幅
    High = re.findall('"f15":(.*?),',response.text) #最高
    Low = re.findall('"f16":(.*?),',response.text) #最低
    Open = re.findall('"f17":(.*?),',response.text) #今开
    Previous_Close = re.findall('"f18":(.*?),',response.text) #昨收
    Volume_Ratio = re.findall('"f10":(.*?),',response.text) #量比
    Turnover_Rate = re.findall('"f8":(.*?),',response.text) #换手率
    Price_Earnings_Ratio = re.findall('"f9":(.*?),',response.text) #市盈率
    PricetoBook_Ratio = re.findall('"f23":(.*?),',response.text) #市净率 

    for index in range(0,len(Company_Name)): #0-19
#涨跌幅(Original_Change_Percentage),振幅(Original_Price_Range)，换手率(Turnover_Rate)
        def Data_percentage(value_list): 
            try:                    
                return f"{int(value_list[index])/100}%"
            except (IndexError, ValueError, TypeError):
                return "-"
#成交额(Original_Turnover) 
        def Display_Turnover(value_list):
            try:
                num = float(value_list[index])
                if num >= 100000000:                    
                    return f"{round(num /100000000,2)}亿元"
                else:
                    return f"{round(num / 10000000, 2)}千万元"
            except (IndexError, ValueError, TypeError):
                    return "-"
#最新价(Latest_Price) 涨跌额(Change_Amount) 最高(High) 最低(Low) 今开(Open) 昨收(Previous_Close) 
# 量比(Volume_Ratio) 市盈率(Price_Earnings_Ratio) 市净率(PricetoBook_Ratio)
        def Display_data(value_list):
            try:                    
                return int(value_list[index])/100
            except (IndexError, ValueError, TypeError):
                return "-"
#成交量(Original_Volume_in_lots)
        def Display_Volume_in_lots(value_list):
            try:
                num = int(value_list[index])
                if num >= 10000:                    
                    return f"{round(num /10000,2)}万"
                else:
                    return int(value_list[index])
            except (IndexError, ValueError, TypeError):
                    return "-"      
        
        index_stock = (page_number-1)*20+index

        a_stock =[
                index_stock,
                # int(Stock_code[index]),
                Company_Name[index],
                # Display_data(Latest_Price), 
                # Data_percentage(Original_Change_Percentage),
                # Display_data(Change_Amount),
                # Display_Volume_in_lots(Original_Volume_in_lots),
                # Display_Turnover(Original_Turnover),
                # Data_percentage(Original_Price_Range),
                # Display_data(High),
                # Display_data(Low),
                # Display_data(Open),
                # Display_data(Previous_Close),
                # Data_percentage(Turnover_Rate),
                # Display_data(Price_Earnings_Ratio),
                # Display_data(Price_Earnings_Ratio),
                # Display_data(PricetoBook_Ratio)
                ]
        
        print(a_stock)
        stock_list.append(a_stock)
        # if stock_list:
        #     DataFrame = pandas.DataFrame(stock_list,columns=stock_list_thead)
        #     DataFrame.to_excel("A股实时数据.xlsx",index=False,engine="openpyxl")
        #     print("success")
        # else:
        #     print("没有获取到任何数据")
